package com.study.thirdlib.litepal

import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import com.study.base.BaseFragment
import com.study.thirdlib.R
import kotlinx.android.synthetic.main.fragment_news_list.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.support.v4.toast
import org.litepal.LitePal
import org.litepal.tablemanager.Connector
import java.util.*

/**
 * <pre>
 *     author : slx
 *     time   : 2020/04/02
 *     desc   :
 * </pre>
 */
class NewsListFragment : BaseFragment() {
    override fun getLayoutId() = R.layout.fragment_news_list

    override fun initView() {
        super.initView()
        insert.onClick {
            insertNews()
        }

        update.onClick {
            updateNews()
        }

        query.onClick {
            queryNews()
        }
    }

    private fun queryNews() {
        //安装id查询一条或多条,isEager参数表示是否查询关联对象，不建议使用关联关系查询影响效率
        val news = LitePal.find(News::class.java, 1/*,true*/)
        //val findAll = LitePal.findAll(News::class.java, 1, 2)
        resultTv.text = news.toString()

        //连缀查询
        /* LitePal
                 .where("title=? and commentCount>?", "xxx", "0")
                 .limit(1)
                 .offset(1)
                 .find(News::class.java)*/

        LitePal.findAsync(News::class.java, 2).listen { list ->
            resultTv.append(list.toString())
        }
    }

    private fun updateNews() {
        //使用LitePal
        val values = ContentValues()
        values.put("name", "macbook真好")
        LitePal.update(News::class.java, values, 2)

        //使用News
        /*val news = News()
        news.update(3)*/

        //将字段设置为默认值无效(news.setCommentCount(0))，需要使用改方法
        //news.setToDefault("commentCount")
    }

    private fun insertNews() {
        val comment1 = Comment(null, "好", null)
        comment1.save()
        val comment2 = Comment(null, "很好", null)
        comment2.save()

        val comments = mutableListOf(comment1, comment2)
        val news = News(0, "好新闻", "新闻闻闻", Date(), 2, null, comments, null)
        val result = news.save()
        if (result) {
            toast("保存成功,id=${news.id}")
        } else toast("保存失败")
    }

    override fun initData() {
        super.initData()
        val database: SQLiteDatabase = Connector.getDatabase()
    }
}